package com.zhl.microservcie.order.service;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhl.microservcie.order.feign.ItemFeignClient;
import com.zhl.microservcie.order.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @program: zhl-microservcie-parent
 * @author: zhl
 * @create: 2019-03-04
 **/
@Service
public class ItemService {

    @Autowired
   private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ItemFeignClient itemFeignClient;

//    @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")
//    public Item queryItemById(Long id){
//        String serviceId = "item-server";
//        return  restTemplate.getForObject("http://"+serviceId+"/item/"+id, Item.class);
//    }

    @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")
    public Item queryItemById(Long id){
        return itemFeignClient.queryItemById(id);
    }

    public Item queryItemByIdFallbackMethod(Long id){
       return  new Item(id, "商品信息错误", null, null, null);
    }

//    public Item queryItemById(Long id){
//        String serviceId = "item-server";
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId);
//        if (serviceInstances.isEmpty()){
//            return null;
//        }
//        ServiceInstance serviceInstance = serviceInstances.get(0);
//        String url = serviceInstance.getHost()+":"+serviceInstance.getPort();
//
//        return  restTemplate.getForObject("http://"+url+"/item/"+id, Item.class);
//    }

//    public Item queryItemById(Long id){
//       return  restTemplate.getForObject("http://192.168.1.193:9501/item/"+id, Item.class);
//    }
}
